package com.liuzhilin.controller;

import com.liuzhilin.service.ManagerService;
import com.liuzhilin.service.UserService;
import com.liuzhilin.util.Response;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.json.JSONObject;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.PrintWriter;
/*
* 管理员登录
* */
@WebServlet("/managerLogin")
public class ManagerLogin extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws IOException {
        // 设置响应头，允许跨域请求
        Response.setCorsHeaders(response);
        System.out.println("test test test!!!!!!!");
        // 设置响应内容类型为 JSON
        response.setContentType("application/json");
        PrintWriter out = response.getWriter();
        BufferedReader reader = request.getReader();
        StringBuilder sb = new StringBuilder();
        String line;
        while ((line = reader.readLine()) != null) {
            sb.append(line);
        }
        JSONObject requestJson = new JSONObject(sb.toString());

        String username = requestJson.getString("username");
        String password = requestJson.getString("password");
        // 验证用户
        if (ManagerService.managerLogin(username, password)) {
            // 登录成功
            String token = "some-generated-token"; // 假设生成了一个 token
            out.print("{\"token\": \"" + token + "\", \"message\": \""+username+"登录成功！\",\"" + "username\":\""+username+"\"}");
            response.setStatus(200);
        } else {
            // 密码错误
            out.print("{\"message\": \"管理员不存在或密码错误！\"}");
            response.setStatus(400);
        }
    }
    @Override
    public void doOptions(HttpServletRequest request, HttpServletResponse response){
        Response.setCorsHeaders(response);
    }
}
